package com.java.atomikos;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Objects;

/**
 * 配置bank1的事务管理、repo包扫描、entity包扫描、dataSource信息
 */
@Configuration
@EnableJpaRepositories(
        basePackages = "com.java.repository.bank1",
        entityManagerFactoryRef = "bank1EntityManager",
        transactionManagerRef = "bank1TransactionManager")
@DependsOn("jtaTransactionManager")
@EnableTransactionManagement
public class Bank1DataSourceConfig {
    @Autowired
    private JpaProperties jpaProperties;

    /**
     * @Primary 配置多个数据源时，选择默认
     */
    @Primary
    @Bean(initMethod = "init", destroyMethod = "close")
    public AtomikosDataSourceBean bank1DataSource() throws Exception {
        AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean();
        // Configure the data source
        MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
        mysqlXADataSource.setUrl("jdbc:mysql://47.107.229.71:3306/testdb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true");
        mysqlXADataSource.setUser("root");
        mysqlXADataSource.setPassword("123456");
        mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true);
        /**
         *使用druid不行，mysql8.0版本会有：XAConnectionFactory: failed to create pooled connection - DBMS down or unreachable 异常
         * DruidXADataSource druidXADataSource = new DruidXADataSource();
         *   druidXADataSource.setUrl("jdbc:mysql://127.0.0.1:3306/bank1?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true");
         * druidXADataSource.setUsername("loginUser");
         * druidXADataSource.setPassword("loginPass");
         * druidXADataSource.setDefaultAutoCommit(false);
         * druidXADataSource.setMaxWait(2000);
         */
        dataSource.setXaDataSource(mysqlXADataSource);
        dataSource.setUniqueResourceName("bank1DataSource");
        dataSource.setPoolSize(10);
        return dataSource;
    }

    @Primary
    @Bean(name = "bank1EntityManager")
    public LocalContainerEntityManagerFactoryBean bank1EntityManager(EntityManagerFactoryBuilder builder) throws Exception {
        return builder.dataSource(bank1DataSource()).jta(true)
                .properties(jpaProperties.getProperties())
                //设置实体类所在位置：类或包
                .packages("com.java.entity.bank1")
                //持久化单元名称
                .persistenceUnit("jta-bank1")
                .build();
    }

    @Primary
    @Bean(name = "bank1TransactionManager")
    public PlatformTransactionManager bank1TransactionManager(EntityManagerFactoryBuilder builder) throws Exception {
        return new JpaTransactionManager(Objects.requireNonNull(bank1EntityManager(builder).getObject()));
    }
}